package com.office.controller;


import com.office.common.Response;
import com.office.mapper.UserMapper;
import com.office.utils.TokenUtils;
import com.office.entity.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;


@RestController
@RequestMapping("/user")
public class UserController{

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    public Response<?> login(@RequestBody User userParam) {
        User user = userMapper.selectByLoginId(String.valueOf(userParam.getLoginId()));

        if (Objects.isNull(user)) {
            return Response.error("-1", "登录号不存在");
        }

        if (!userParam.getPassword().equals(user.getPassword())) {
            return Response.error("-1", "密码错误");
        }

        String token = TokenUtils.genToken(user);
        user.setToken(token);

        return Response.success(user);
    }

    @PostMapping("/register")
    public Response<?> register(@RequestBody User user) {
        User userExist = userMapper.selectByLoginId(String.valueOf(user.getLoginId()));

        if (!Objects.isNull(userExist)) {
            return Response.error("-1", "登录号已注册");
        }

        User userInfo = User.builder()
                .username(user.getLoginId().toString())
                .password(user.getPassword())
                .avatar("https://web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg")
                .age(23)
                .sex("男")
                .loginId(user.getLoginId())
                .build();

        userMapper.insert(userInfo);
        return Response.success();
    }

    //test
    @GetMapping("/{id}")
    public Response<?> getById(@PathVariable Integer id) {
        return Response.success(userMapper.selectById(id));
    }

}
